#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize)
{
    if (matrixSize == 0 || matrixColSize[0] == 0)
    {
        *returnSize = 0;
        return NULL;
    }
    *returnSize = matrixSize * (*matrixColSize);
    int* ret = (int*)malloc(sizeof(int) * (*returnSize));
    int* cur = ret;
    int down = matrixSize - 1;
    int right = *matrixColSize - 1;
    int up = 0;
    int left = 0;
    int size = 0;
    int i = 0;
    while (left <= right && up <= down)
    {
        for (i = left; i <= right; i++)
        {
            cur[size] = matrix[up][i];
            size++;
            if (size == *returnSize)
                return ret;
        }
        up++;
        for (i = up; i <= down; i++)
        {
            cur[size] = matrix[i][right];
            size++;
            if (size == *returnSize)
                return ret;
        }
        right--;
        for (i = right; i >= left; i--)
        {
            cur[size] = matrix[down][i];
            size++;
            if (size == *returnSize)
                return ret;
        }
        down--;
        for (i = down; i >= up; i--)
        {
            cur[size] = matrix[i][left];
            size++;
            if (size == *returnSize)
                return ret;
        }
        left++;
    }
    return ret;
}


int** generateMatrix(int n, int* returnSize, int** returnColumnSizes)
{
    *returnSize = n;
    *returnColumnSizes = (int*)malloc(sizeof(int) * n);
    for (int i = 0; i < n; i++)
    {
        (*returnColumnSizes)[i] = n;
    }
    int** ret = (int**)malloc(sizeof(int*) * n);
    for (int i = 0; i < n; i++)
    {
        ret[i] = (int*)malloc(sizeof(int) * n);
    }
    int left = 0;
    int up = 0;
    int right = n - 1;
    int down = n - 1;
    int num = 1;
    while (left <= right && up <= down)
    {
        for (int i = left; i <= right; i++)
        {
            ret[up][i] = num;
            num++;
        }
        up++;
        for (int i = up; i <= down; i++)
        {
            ret[i][right] = num;
            num++;
        }
        right--;
        for (int i = right; i >= left; i--)
        {
            ret[down][i] = num;
            num++;
        }
        down--;
        for (int i = down; i >= up; i--)
        {
            ret[i][left] = num;
            num++;
        }
        left++;
    }
    return ret;
}


int main()
{
    int** spin = (int**)malloc(sizeof(int*) * 3);
    for (int i = 0; i < 3; i++)
    {
        spin[i] = (int*)malloc(sizeof(int) * 3);
    }
    int size = 3;
    int* ColumnSizes = (int*)malloc(sizeof(int) * 3);
    spin = generateMatrix(9, &size, &ColumnSizes);
    int* nums = (int*)malloc(sizeof(int) * 9);
    int nums_size = 0;
    int* nums_colSize = (int*)malloc(sizeof(int) * 3);
    for (int i = 0; i < 3; i++)
    {
        nums_colSize[i] = 3;
    }
    nums = spiralOrder(spin, 9,nums_colSize, &nums_size);
    return 0;
}